<template>
  <div class="ctfQuestion-warp" style="position: relative;">
    <div class="floatWrap">
      <Button
        ghost
        style="height: 32px;margin-right: 15px"
        type="primary"
        icon="ios-cloud-upload-outline"
        v-if="distributed"
        @click="reportedQuestions"
        >主观题上报</Button
      >

      <Checkbox v-model="creatByMeModal" @on-change="searchCreatedByMe" style="flex-shrink: 0"
        >由我创建</Checkbox
      >
<!--      <Divider type="vertical" />-->
      <Select filterable
        @on-change="searchItem"
        v-model="queryCtfInfo.rangeId"
        style="width:155px"
        :placeholder="'靶场:' + mainRange"
        clearable
        v-if="distributedRange"
      >
        <Option v-for="(items, index) in rangeAllList" :value="items.id" :key="index + 'range'">{{
          items.name
        }}</Option>
      </Select>
      <Select filterable
        v-model="queryCtfInfo.matchMode"
        style="width:150px;margin-left: 15px;"
        clearable
        placeholder="题型"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option v-for="matchMode in matchModeList" :key="matchMode.value" :value="matchMode.value">{{matchMode.label}}</Option>
        <!-- <Option value="1" v-if="hasAWD || hasCtf || hasST">{{
            `${hasAWD ? awdContest : ''}${hasCtf ? '/夺旗' : ''}${hasST ? '/渗透' : ''}`
        }}</Option>
        <Option value="2" v-if="(hasCtf || hasST) && !hasAWD">{{
            `${hasCtf ? '夺旗' : ''}${hasST ? '/渗透' : ''}`
        }}</Option>
        <Option value="3">问答题</Option>
        <Option value="4" v-if="hasAWDPlus">{{awdPlusContest}}</Option> -->
      </Select>
      <Select filterable
        clearable
        v-model="queryCtfInfo.needEnv"
        style="width:150px;margin-left: 15px"
        placeholder="需要环境"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option value="1">是</Option>
        <Option value="0">否</Option>
      </Select>
      <Select filterable
        v-model="queryCtfInfo.docFlag"
        style="width:150px;margin-left: 15px"
        clearable
        placeholder="有解题思路文档"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option value="1">是</Option>
        <Option value="0">否</Option>
      </Select>
      <Select filterable
          multiple
          clearable
          v-model="queryCtfInfo.applicationList"
          style="width:150px;margin-left: 15px"
          placeholder="题目用途"
          @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option v-for="(label,value) in applist" :value="value" :key="value">{{label}}</Option>
      </Select>
      <Select filterable
        clearable
        v-model="queryCtfInfo.visibility"
        style="width:150px;margin-left: 15px"
        placeholder="可见范围"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option value="public">系统</Option>
        <Option value="share">单位</Option>
        <Option value="private">个人</Option>
      </Select>
      <Select filterable
        clearable
        v-model="queryCtfInfo.flagType"
        style="width:150px;margin-left: 15px"
        placeholder="验证类型"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option value="1">非固定Flag</Option>
        <Option value="0">固定Flag</Option>
        <Option value="2">Checker</Option>
        <Option value="3">提交报告</Option>
      </Select>
      <Select filterable
        v-model="queryCtfInfo.category"
        style="width:150px;margin-left: 15px"
        clearable
        placeholder="主观题类型"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
      >
        <Option
          :value="category.dictname"
          v-for="category in questionTypeList"
          :key="category.dictname"
          :title="category.dictname"
          >{{ category.dictname }}</Option
        >
      </Select>
      <Input
        v-model.trim="queryCtfInfo.name"
        placeholder="主观题名称"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
        style="width:180px;margin-left: 15px;"
        clearable
      ></Input>
      <Input
        v-model.trim="queryCtfInfo.imageName"
        placeholder="镜像名称"
        style="width:180px;margin-left: 15px;"
        @on-change="
          query.pageIndex = 1;
          queryCtfList();
        "
        clearable
      ></Input>
      
      
      <Button type="primary" ghost class="md-add-jh" style="margin-left: 15px;"
      @click="addQuestionTip"><i class="el-icon-edit"></i>创建</Button>
      
      <Button
        class="header-btn"
        type="primary"
        ghost
        style="height: 32px;margin-left: 15px;"
        @click="refreshCtfQuesList()"
        ><i class="el-icon-refresh-right"
      /></Button>
    </div>
    <!-- <div v-show="showDataList"> -->
      <!-- <div style="padding:15px 0 0 0;" v-if="selectQuestions.length > 0">
        <Tag
          type="border"
          closable
          color="primary"
          v-for="question in selectQuestions"
          :key="question.id"
          @on-close="checkSingleQuestion(false, question)"
          >{{ question.name }}</Tag
        >
      </div> -->
      <div class="page-content">
        <TableList 
            ref="searchTable"
            :data="ctfList" 
            :columns="ctfCol"
            :page.sync="query.pageIndex"
            :size.sync="query.pageSize"
            :total="totalCount"
            :loading="tableLoading"
            showSelectTag
            :selection.sync="selectQuestions" 
            @queryFun="queryCtfList">
          </TableList>
    </div>

    <Modal
      v-model="ctfModal.show"
      :title="ctfModal.title"
      @on-ok="saveCtf"
      @on-cancel="initForms"
      :loading="ctfModal.loading"
      width="550"
      :mask-closable="false"
    >
      <Form
        :label-width="80"
        :model="formValidate"
        :rules="ruleValidate"
        ref="formValidate"
        style="width:500px"
      >
        <FormItem label="题目名称" prop="name" key="name">
          <Input v-model.trim="formValidate.name" placeholder="题目名称长度为1-128个字符"></Input>
        </FormItem>

        <FormItem label="类型" prop="category" key="category">
          <Select filterable
            v-model="formValidate.category"
            placeholder="选择类型"
            @on-change="changeCategory"
          >
            <Option
              :value="category.dictname"
              v-for="category in questionTypeList"
              :key="category.dictname"
              :title="category.dictname"
              >{{ category.dictname }}</Option
            >
          </Select>
        </FormItem>


<!--        0 考试和竞赛，1 练习  ，2 通用；默认 0-->
        <FormItem label="题目用途" prop="application" key="application">
          <RadioGroup v-model="formValidate.application">
          <Radio  v-for="(dict,value) in dictEntryList" :label="dict.key" :key="dict.key">{{dict.value}}</Radio>
          </RadioGroup>
        </FormItem>
        
        
        
        <FormItem label="可见范围" prop="visibility" key="visibility">
          <RadioGroup v-model="formValidate.visibility" @on-change="changePublic">
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
          <Tooltip
            v-if="formValidate.chaId"
            style="margin-left: 10px;"
            :transfer="true"
            max-width="200"
            content="可见范围由个人修改为单位时，主观题使用的个人资源(镜像、文档)的可见范围将变为单位"
            placement="top"
          >
            <Icon type="ios-alert" class="ios-alert" />
          </Tooltip>
        </FormItem>
        <FormItem label="题型" prop="matchMode" key="matchMode">
          <RadioGroup v-model="formValidate.matchMode" @on-change="setFormInfo">
            <Radio v-for="matchMode in matchModeList" :key="matchMode.value" :label="matchMode.value">{{matchMode.label}}</Radio>
            <!-- <Radio label="2">夺旗/渗透</Radio>
            <Radio label="1">攻防/夺旗/渗透</Radio> -->
            <!-- <Radio label="1" v-if="hasAWD || hasCtf || hasST">{{
              `${hasAWD ? '攻防' : ''}${hasCtf ? '/夺旗' : ''}${
                  hasST ? '/渗透' : ''
              }`
            }}</Radio>
            <Radio label="2" v-if="hasCtf || hasST">{{
                `${hasCtf ? '夺旗' : ''}${hasST ? '/渗透' : ''}`
            }}</Radio>
            <Radio label="3">问答题</Radio>
            <Radio label="4" v-if="hasAWDPlus">攻防plus</Radio> -->
          </RadioGroup>
        </FormItem>
        <FormItem
          label="部署环境"
          prop="needEnv"
          v-if="formValidate.matchMode === '2'"
          key="needEnv"
        >
          <RadioGroup v-model="FormValidate.needEnv" @on-change="setFormInfo1">
            <Radio label="1">是</Radio>
            <Radio label="0" :disabled="formValidate.category === '安全运维'">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="虚拟化类型"
          prop="virtualization"
          v-if="FormValidate.needEnv === '1'"
          key="virtualization"
        >
          <RadioGroup v-model="formValidate.virtualization">
            <Radio label="kvm" :disabled="formValidate.matchMode === '4'">kvm</Radio>
            <Radio label="docker" :disabled="formValidate.matchMode === '4'">docker</Radio>
          </RadioGroup>
        </FormItem>
        <!-- <FormItem
          label="镜像来源"
          prop="ImageSource"
          v-if="FormValidate.needEnv === '1'"
          key="ImageSource"
        >
          <RadioGroup v-model="FormValidate.ImageSource" @on-change="setImageSource">
            <Radio label="1">选择已有镜像</Radio>
            <Radio label="0">上传Docker</Radio>
          </RadioGroup>
        </FormItem> -->
        <FormItem
          label="选择运行环境"
          prop="dockerContent.tempId"
          key="dockerContentTempId"
          v-if="FormValidate.ImageSource === '0' && FormValidate.needEnv === '1'"
        >
          <Select filterable v-model="formValidate.dockerContent.tempId" filterable label-in-value>
            <Option
              v-for="item in dockerList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              :title="item.name"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem
          label="Docker文件"
          prop="dockerContent.dockerName"
          key="dockerContentDockerName"
          v-if="FormValidate.ImageSource === '0' && FormValidate.needEnv === '1'"
        >
          <section>
            <Row>
              <Upload
                ref="uploadDocker"
                :action="uploadDockerUrl"
                :show-upload-list="false"
                :on-success="getDockerUrl"
                :on-progress="getProgress"
                :before-upload="handleBeforeUploadDocker"
                :headers="uploadHeader"
                style="display:inline-block;"
              >
                <Button icon="ios-cloud-upload-outline" :disabled="uploadDockerList.length > 0"
                  >上传Docker文件</Button
                >
              </Upload>
              <!-- <span style="color:#ff9900"> <Icon type="ios-information-circle-outline" />请上传doc,docx,pdf等格式文件,文件大小不能超过20M</span> -->

              <!--{{filename}}-->
            </Row>
            <div class="demo-upload-list" v-for="item in uploadDockerList">
              <template v-if="item.status === 'finished'"> </template>
              <template v-else>
                <span style="margin-right:5px;">文件名：{{ item.name }}</span>
                <span style="margin-right:5px;">文件大小：{{ getFileSize(item.size) }}</span>
                <span style="margin-right:5px;">上传速度：{{ speed }}</span>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <div class="chose-wrap" v-show="dockerFilename">
              <div style="display: flex;justify-content: flex-start;align-items: center">
                <img src="@/assets/exper/guide.png" class="chose-s2-icon" />
                <div class="chose-name">{{ dockerFilename }}</div>
              </div>
              <img
                src="@/assets/globalIcon/dis-del.png"
                style="width: 13px;height: 14px;cursor: pointer"
                @click="clearDocker"
              />
            </div>
            <!-- <p v-if="showTip" style="color:red;">请上传doc,pdf格式文件,文件大小不能超过20M</p> -->
            <!-- <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传文件</div> -->
          </section>
        </FormItem>
        <FormItem
          label="Docker内flag路径"
          prop="dockerContent.flagPath"
          key="dockerContentFlagPath"
          v-if="FormValidate.ImageSource === '0' && FormValidate.needEnv === '1'"
        >
          <Input
            v-model.trim="formValidate.dockerContent.flagPath"
            placeholder="Linux:/xxx/文件名称"
          ></Input>
        </FormItem>
        <FormItem
          label="Docker运行命令及参数"
          prop="dockerContent.cmd"
          key="dockerContentCmd"
          v-if="FormValidate.ImageSource === '0' && FormValidate.needEnv === '1'"
        >
          <Input v-model.trim="formValidate.dockerContent.cmd"></Input>
          <Tooltip
            class="ios-alert1"
            style="margin-left: 10px;"
            :transfer="true"
            max-width="400"
            placement="top"
          >
            <Icon type="ios-alert" />
            <div slot="content">
              <p>docker 镜像名称用 %s 代替</p>
              <p>
                docker run -d --name=server-db -p 3306:3306
                <i style="color:#fd5f5f">centos6.8-mysql</i> /usr/bin/mysql_safe –d
              </p>
              <p>
                docker run -d --name=server-db -p 3306:3306
                <i style="color:#fd5f5f">%s</i> /usr/bin/mysql_safe –d
              </p>
            </div>
          </Tooltip>
        </FormItem>
        <FormItem
          class="SelForm"
          label="选择镜像"
          prop="imageId"
          v-if="FormValidate.needEnv === '1' && FormValidate.ImageSource === '1'"
          key="imageId"
        >
          <Select filterable
            v-model="formValidate.imageId"
            @on-change="getImageInfo"
            label-in-value
            filterable
          >
            <Option
              v-for="item in formValidate.virtualization == 'kvm'?imageList1:imageList2"
              :key="item.id"
              :value="item.id"
              :label="item.imageName"
              :title="item.imageName"
              :disabled="
                (formValidate.visibility == 'share' || !isOwn) && item.localVisibility == 'private'
              "
            >
            </Option>
          </Select>
          <Button
            type="text"
            size="small"
            @click="addImage"
            icon="md-add"
            class="AddImageBtn"
          ></Button>
        </FormItem>
        <FormItem
          label="选择配额"
          prop="flavorRef"
          v-if="FormValidate.needEnv === '1'"
          key="flavorRef"
        >
          <Select filterable
            v-model="formValidate.flavorRef"
            @on-change="getFlavorInfo"
            label-in-value
            filterable
          >
            <Option
              v-for="item in flavorList"
              :key="item.id"
              :value="item.id"
              :label="item.flavorName"
              :title="item.flavorName"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem
          :label="formValidate.matchMode !== '4' ? '端口' : '攻击机端口'"
          prop="port"
          v-if="FormValidate.needEnv === '1'"
          key="port"
        >
          <Input v-model.trim="formValidate.port" placeholder="请输入1-65535的整数"></Input>
        </FormItem>
        <FormItem
          label="防守机端口"
          prop="defensivePort"
          v-if="formValidate.matchMode === '4'"
          key="defensivePort"
        >
          <Input
            v-model.trim="formValidate.defensivePort"
            placeholder="请输入1-65535的整数"
          ></Input>
        </FormItem>
        <FormItem
          label="检测脚本"
          prop="scriptId"
          v-if="FormValidate.needEnv === '1'"
          key="scriptId"
        >
          <Select filterable
            v-model="formValidate.scriptId"
            placeholder="请选择检测脚本"
            filterable
            key="script-select"
            clearable
          >
            <Option
              v-for="item in checkerList"
              :key="item.id"
              :value="item.id"
              @mouseenter.native="mouseOverConfiger($event, item.id)"
              @mouseleave.native="mouseLeaveConfiger($event, item.id)"
              @click.stop.prevent="configurationInformation = false"
              >{{ item.name }}</Option
            >
          </Select>
          <div
            v-show="configurationInformation"
            :style="{
              position: 'absolute',
              left: cardPanelLeft,
              top: cardPanelTop,
              zIndex: '9999999999999999'
            }"
            @mouseenter="jinru"
            @mouseleave="yichu"
            @click.stop.prevent
          >
            <Card :style="{ minWidth: '350px', maxWidth: '600px' }">
              <p slot="title" style="position:relative">
                <Icon type="ios-construct"></Icon>
                {{ configPanel.configName }}
                <span slot="title" style="position:absolute;right:0px">
                  <Icon type="ios-contact"></Icon>
                  {{ configPanel.configCreatorName }}
                </span>
              </p>
              <ul>
                <li><span class="_dot"></span>path：{{ configPanel.configPath }}</li>
                <li><span class="_dot"></span>argArr：{{ configPanel.configArg }}</li>
                <li><span class="_dot"></span>cmd：{{ configPanel.configCmd }}</li>
                <li><span class="_dot"></span>sysType：{{ configPanel.configSystype }}</li>
                <li><span class="_dot"></span>protocol：{{ configPanel.protocol }}</li>
                <li><span class="_dot"></span>serverPort：{{ configPanel.serverPort }}</li>
                <li><span class="_dot"></span>language：{{ configPanel.language }}</li>
                <li><span class="_dot"></span>CreateTime：{{ configPanel.configCreateTime }}</li>
                <li><span class="_dot"></span>Desc：{{ configPanel.configDescription }}</li>
              </ul>
            </Card>
          </div>
        </FormItem>
        <FormItem
          label="重置攻击机脚本"
          prop="attackScript"
          v-if="formValidate.matchMode === '4'"
          key="attackScript"
        >
          <Input
            v-model.trim="formValidate.attackScript"
            placeholder="请输入重置攻击机脚本"
          ></Input>
        </FormItem>
        <!-- 只有攻防赛plus类型的docker需要添加防守机脚本 -->
        <FormItem
          label="重置防守机脚本"
          prop="defenseScript"
          v-if="formValidate.matchMode === '4'"
          key="defenseScript"
        >
          <Input
            v-model.trim="formValidate.defenseScript"
            placeholder="请输入重置防守机脚本"
          ></Input>
        </FormItem>
        <FormItem
          label="提交Flag"
          prop="submitFlag"
          v-if="formValidate.matchMode === '2'"
          key="submitFlag"
        >
          <RadioGroup v-model="formValidate.submitFlag" @on-change="changeNeedSubmitFlag">
            <Radio label="1" :disabled="formValidate.category === '安全运维'">是</Radio>
            <Radio label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="验证类型"
          prop="flagType"
          key="flagType"
          v-if="
            formValidate.submitFlag === '1' &&
              (formValidate.matchMode === '2' || formValidate.matchMode === '4')
          "
        >
          <RadioGroup v-model="formValidate.flagType">
            <Radio label="0">固定Flag</Radio>
            <Radio label="1" v-if="FormValidate.needEnv === '1'"
              >非固定Flag（静态Flag | 动态Flag）</Radio
            >
            <!--
					<Radio label="2">Checker</Radio>
					-->
          </RadioGroup>
          <!-- 感觉重复了，注释掉一个 -->
          <!-- <Button
            v-if="formValidate.flagType === '0'"
            @click="addFlag()"
            shape="circle"
            icon="ios-add"
            >添加flag</Button
          > -->
        </FormItem>
        <FormItem
          label="Flag路径"
          prop="flagPath"
          key="flagPath"
          v-if="formValidate.flagType === '1' && formValidate.category !== '安全运维'"
        >
          <Input type="textarea" v-model.trim="formValidate.flagPath"></Input>
        </FormItem>
        <div
          v-if="
            formValidate.flagType === '1' &&
              formValidate.submitFlag === '1' &&
              formValidate.category !== '安全运维'
          "
        >
          <FormItem label="匹配类型" prop="flagMatchType" key="flagMatchType">
            <RadioGroup v-model="formValidate.flagMatchType">
              <Radio label="0">严格匹配</Radio>
              <Radio label="1">模糊匹配</Radio>
            </RadioGroup>
          </FormItem>
        </div>
        <FormItem
          label="分值"
          prop="score"
          key="score"
          v-if="
            (formValidate.flagType == '1' && formValidate.submitFlag == '1') ||
              formValidate.matchMode == '3' ||
              formValidate.submitFlag == '0'
          "
        >
          <InputNumber
            v-model="formValidate.score"
            :min="1"
            placeholder="Enter something..."
          ></InputNumber>
        </FormItem>

        <div v-if="formValidate.flagType === '0' && formValidate.submitFlag === '1'">
          <div v-for="(item, index) in formValidate.answers" :key="index">
            <Divider />
            <div style="display:flex;justify-content: space-between;margin-bottom:15px">
              <span>第{{ index + 1 }}个Flag</span>
              <Button
                v-if="formValidate.flagType === '0' && index == 0"
                @click="addFlag()"
                shape="circle"
                icon="ios-add"
                >添加flag</Button
              >
            </div>
            <FormItem
              label="Flag"
              :prop="'answers.' + index + '.flag'"
              :rules="[
                { required: true, message: '请填写flag内容', trigger: 'blur' },
                {
                  validator: (rule, value, callback) => {
                    let copyAnswers = JSON.parse(JSON.stringify(formValidate.answers));
                    copyAnswers.splice(index, 1);
                    if (item.flag && copyAnswers.map((answer) => answer.flag).includes(item.flag)) {
                      callback('Flag内容不能相同');
                    } else {
                      callback();
                    }
                  }
                }
              ]"
              key="flag"
            >
              <Input type="textarea" v-model="item.flag"></Input>
            </FormItem>
            <FormItem
              label="匹配类型"
              :prop="'answers.' + index + '.flagMatchType'"
              :rules="{ required: true, message: '不能为空', trigger: 'blur' }"
              key="flagMatchType"
              v-if="formValidate.flagType === '0' && formValidate.submitFlag === '1'"
            >
              <RadioGroup v-model="item.flagMatchType">
                <Radio label="0" :disabled="formValidate.flagType === '0'">严格匹配</Radio>
                <Radio label="1" :disabled="formValidate.flagType === '0'">模糊匹配</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              label="分值"
              :prop="'answers.' + index + '.score'"
              :rules="ruleValidate.score"
              key="score"
            >
              <InputNumber
                v-model="item.score"
                :min="1"
                placeholer="Enter something..."
              ></InputNumber>
              <Button @click="delflag(index)" v-if="index + 1 == flagNumber">删除</Button>
            </FormItem>
          </div>
        </div>
         <FormItem label="参考答案" prop="flagTxt" key="flagTxt" v-if="formValidate.matchMode==='3'">
						<Input type="textarea" v-model.trim="formValidate.flagTxt"></Input>
				</FormItem>
        <!-- <FormItem label="Flag" prop="flagTxt" key="flagTxt" v-if="formValidate.flagType==='0'">
						<Input type="textarea" v-model.trim="formValidate.flagTxt"></Input>
				</FormItem>
				<FormItem label="Flag路径" prop="flagPath" key="flagPath" v-if="formValidate.flagType==='1'">
						<Input type="textarea" v-model.trim="formValidate.flagPath"></Input>
				</FormItem>
				<div v-if="formValidate.submitFlag === '1' && formValidate.matchMode != '3'">
					<FormItem label="匹配类型" prop="flagMatchType" key="flagMatchType" >
						<RadioGroup v-model="formValidate.flagMatchType">
							<Radio label="0">严格匹配</Radio>
							<Radio label="1">模糊匹配</Radio>
						</RadioGroup>
					</FormItem>
				</div>
				<FormItem label="分值" prop="score" key="score" >
						<InputNumber v-model="formValidate.score" :min="1" :max="1000"  placeholder="Enter something..."></InputNumber>
				</FormItem> -->
        <!-- :format="['doc','docx','']" -->
        <FormItem label="解题思路" prop="writeUpPath" key="writeUpPath">
          <section>
            <Row>
              <Upload
                ref="upload"
                :action="uploadAction"
                :format="['doc', 'docx', 'pdf']"
                :show-upload-list="false"
                :on-format-error="handleFormatError"
                :on-success="getImageUrl"
                :on-progress="getProgress"
                :before-upload="handleBeforeUpload"
                :headers="uploadHeader"
                style="display: inline-block;"
              >
              <!-- :on-exceeded-size="handleUploadSize" -->
                <Button
                  icon="ios-cloud-upload-outline"
                  :disabled="uploadList[0] && uploadList[0].status != 'finished'"
                  >上传解题思路文件</Button
                >
              </Upload>
              <Tooltip
                style="margin-left: 10px;"
                :transfer="true"
                max-width="200"
                content="请上传doc,docx,pdf格式文件"
                placement="top"
              >
                <Icon type="ios-alert" class="ios-alert" />
              </Tooltip>
              <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                <template v-if="item.status === 'finished'"> </template>
                <template v-else>
                  <span style="margin-right:5px;">文件名：{{ item.name }}</span>
                  <span style="margin-right:5px;">文件大小：{{ getFileSize(item.size) }}</span>
                  <span style="margin-right:5px;">上传速度：{{ speed }}</span>
                  <Progress
                    v-if="item.showProgress"
                    :percent="item.percentage"
                    text-inside
                  ></Progress>
                </template>
              </div>
              <div class="chose-wrap" v-show="filename">
                <div style="display: flex;justify-content: flex-start;align-items: center">
                  <img src="../../../../assets/exper/guide.png" class="chose-s2-icon" />
                  <div class="chose-name">{{ filename }}</div>
                </div>
                <img
                  src="../../../../assets/globalIcon/dis-del.png"
                  style="width: 13px;height: 14px;cursor: pointer"
                  @click="clearDoc"
                />
              </div>
              <img
                :src="iconSrc"
                style="width:100%;height:auto;margin-left: 30px;"
                v-if="formValidate.iconPath"
              />
            </Row>
            <p v-if="showTip" style="color:red;">
              文件格式错误:请上传doc,docx,pdf解题思路文件
            </p>
            <!-- ,文件大小不能超过20M -->
            <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传解题思路文件</div>
          </section>
        </FormItem>
        <!--ctfModal.type == 2 && -->
        <FormItem label="题目附件" prop="attachment" key="attachment">
          <!--<Button type="primary" @click="tagModal.show = true">标签</Button>-->
          <!--<Button type="primary" @click="fileModal.show = true">题目附件</Button>-->
          <!--<Button type="primary" @click="urlModal.show = true">Urls</Button>
					<Button type="primary" @click="answerModal.show = true">Keys</Button>-->
          <ctfFile
            v-if="ctfModal.show"
            @setAttachmentFile="getAttachmentFile"
            :curSaveFile="curSaveFile"
          ></ctfFile>
        </FormItem>
        <FormItem label="描述" prop="description" key="description">
          <Input
            v-model.trim="formValidate.description"
            type="textarea"
            :maxlength="1000"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述信息"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="detailModal" title="题目详情" :mask-closable="false" :width="800" footer-hide>
      <div id="quesDetail">
        <p>
          <span class="label">名称</span><span>{{ curQues.name }}</span>
        </p>
        <p>
          <span class="label">类型</span><span>{{ curQues.category }}</span>
        </p>
        <p>
          <span class="label">可见范围</span
          ><span :style="{ color: setVisibility(curQues.visibility).color }">{{
            setVisibility(curQues.visibility).text
          }}</span>
        </p>
        <p>
          <span class="label">题型</span
          ><span>{{
            getMatchMode(curQues.matchMode)
          }}</span>
          <!--    curQues.matchMode == '1'
              ? '攻防/夺旗/渗透'
              : curQues.matchMode == '2'
              ? '夺旗/渗透'
              : curQues.matchMode == '3'
              ? '问答题'
              : '攻防plus' --> 
        </p>
        <p>
          <span class="label">分值</span><span>{{ curQues.score }}</span>
        </p>
        <p>
          <span class="label">需要环境</span
          ><span>{{ curQues.imageId || curQues.dockerEnvName ? '是' : '否' }}</span>
        </p>
        <p v-if="curQues.imageId ? true : false">
          <span class="label">镜像</span><span>{{ curQues.imageName }}</span>
        </p>
        <p v-if="curQues.dockerEnvName ? true : false">
          <span class="label">docker内运行环境</span><span>{{ curQues.dockerEnvName }}</span>
        </p>
        <p v-if="curQues.imageId || curQues.dockerEnvName ? true : false">
          <span class="label">配额</span><span>{{ curQues.flavorName }}</span>
        </p>
        <p v-if="curQues.imageId || curQues.dockerEnvName ? true : false">
          <span class="label">
            {{ curQues.matchMode !== '4' ? '端口' : '攻击机端口' }} </span
          ><span>{{ curQues.port }}</span>
        </p>
        <p v-if="(curQues.imageId || curQues.dockerEnvName) && curQues.matchMode === '4'">
          <span class="label">防守机端口</span><span>{{ curQues.defensivePort }}</span>
        </p>
        <p>
          <span class="label">提交Flag</span
          ><span>{{ curQues.submitFlag == 0 ? '否' : '是' }}</span>
        </p>
        <p>
          <span class="label">验证类型</span><span>{{ typeFilter(curQues.flagType) }}</span>
        </p>
        <p v-if="curQues.submitFlag == 1 && curQues.flagType == 1">
          <span class="label">Flag路径</span><span>{{ curQues.flagPath }}</span>
        </p>
        <p
          v-if="curQues.submitFlag == 1 && curQues.flagType == 0 && curQues.flagTxt == ''"
          v-for="(item, index) of curQues.answers"
          :key="index"
        >
          <span class="label">第{{ index + 1 }}个Flag:</span><span>{{ item.flag }}</span>
        </p>
        <p v-if="curQues.matchMode == '3' && curQues.flagTxt != ''">
          <span class="label">参考答案</span><span>{{ curQues.flagTxt }}</span>
        </p>
        <p v-if="curQues.submitFlag == 1 && curQues.flagType == 0">
          <span class="label">Flag匹配类型</span
          ><span>{{ curQues.flagMatchType == 0 ? '严格匹配' : '模糊匹配' }}</span>
        </p>
        <p>
          <span class="label">有解题思路文档</span
          ><span>{{ curQues.writeUpPath ? '是' : '否' }}</span>
        </p>
        <p v-if="curQues.writeUpPath ? true : false">
          <span class="label">解题思路</span><span>{{ curQues.writeUpName }}</span>
        </p>
        <p>
          <span class="label">有附件</span
          ><span>{{ curQues.attachmentPath ? '是' : '否' }}</span>
        </p>
        <p>
          <span class="label">检测脚本</span
          ><span>{{ curQues.scriptName ? curQues.scriptName : '-' }}</span>
        </p>
        <p v-if="curQues.matchMode === '4'">
          <span class="label">重置攻击机脚本</span
          ><span>{{ curQues.attackScript ? curQues.attackScript : '-' }}</span>
        </p>
        <p v-if="curQues.matchMode === '4'">
          <span class="label">重置防守机脚本</span
          ><span>{{ curQues.defenseScript ? curQues.defenseScript : '-' }}</span>
        </p>
        <p v-if="curQues.attachmentPath ? true : false">
          <span class="label">附件</span><span>{{ curQues.attachmentName }}</span>
        </p>
        <p>
          <span class="label">描述</span><span>{{ curQues.description }}</span>
        </p>
      </div>
    </Modal>
    <!-- 脚本操作 -->
    <Checker ref="check" @changeImage="screenSelector" @queryCtfList="queryCtfList"></Checker>
  </div>
</template>
<script>
import {
  bindScriptResource,
  deleteScriptResource,
  getScriptResource,
  createCtf,
  modifyCtf,
  delCtf,
  queryCtfList,
  getallImage,
  getallFlavor
} from '@/api/question';
import ctfFile from './ctfFile_new.vue';
import encryption from '@/libs/encryption.js';
import { experType } from '@/api/dict';
import { getAllDocker, getOperateInfo } from '@/api/target.js';
import { reportedQuestions, getRangeAll } from '@/api/reported-data';
import { loadConfiguration } from '@/api/drill';
import Checker from '@/components/checker/Checker';
import resourcesReportedMixin from '@/mixin/resources-reported-mixin';
import { debounce } from '@/libs/utils';
import { validateNameCustom,newValidationRules} from '@/libs/reg.js'
import { mapGetters } from 'vuex'
export default {
  name:'CtfQues',
  components: {
    //			ctfTag,
    //			ctfUrl,
    //			ctfAnswer,
    ctfFile,
    Checker
  },
  mixins: [resourcesReportedMixin],
  props: ['show'],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    const validatePort = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp(
        '^(([1-9]\\d{0,3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$'
      );
      //验证警戒值
      if (value) {
        if (!reg.test(Number(value))) {
          callback(new Error('请输入1-65535的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateScore = (rule, value, callback) => {
      //验证只能填入数字
      // var reg = new RegExp('^[1-9]\d*$');
      //验证警戒值
      if (!value) {
          callback(new Error('请输入正整数分值'));
      } else {
          if (value < 1) {
              callback(new Error('请输入正整数分值'));
          } else {
              callback()
          }
      }
    };
     const validateName = (rule, value, callback) => {
      //验证警戒值
      if (value) {
        validateNameCustom(rule, value, callback, 128)
      } else {
        callback()
      }
    }

    return {
      mainRangeflag: true,
      mainRange: '',
      checkerList: [], // checker列表
      configurationInformation: false,
      hoverCdraBol: false,
      showErrorText: false,
      cardPanelLeft: '3px',
      cardPanelTop: '3px',
      configPanel: {
        configPath: '',
        configSystype: '',
        configContent: '',
        configDescription: '',
        configCreateTime: '',
        configCreatorName: '',
        configName: '',
        configType: '',
        configArg: '',
        configCmd: '',
        protocol: '',
        serverPort: '',
        language: ''
      },
      rangeAllList: [],
      selectAllQuestion: false,
      selectQuestions: [],
      questionTypeList: [], // 题目类型
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      distributed: September.distributed,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setHei: 'auto',
      queryCtfInfo: {
        needEnv: ''
      },
      query: {
        // 查询列表的查询字符串参数
        pageIndex: 1,
        pageSize: 10
      },
      creatByMeModal: false,
      tableLoading: false,
      ctfList: [],
      ctfCol: [
        {
            type: 'selection',
            width: 60,
            align: 'left',
            show:() => {
              return this.distributed
            }
        },
        {
            type:'link',
            title: '主观题名称',
            key: 'name',
            minWidth: 100,
            tooltip: true,
            on:{
              click:(data) => {
                this.showDetail(data)
              }
            }
        },

        {
            title: '镜像名称',
            key: 'imageName',
            minWidth: 60,
            tooltip: true
        },
        {
            title: '分值',
            key: 'score',
            minWidth: 60,
            tooltip: true
        },
        {
            title: '主观题类型',
            key: 'category',
            minWidth: 60,
            tooltip: true
        },
        {
            title: '题型',
            key: 'matchMode',
            minWidth: 60,
            tooltip: true,
            filter: (matchMode) => {
                return this.getMatchMode(matchMode)
                // return matchMode == '1'
                //     ? `${this.hasAWD ? '攻防' : ''}${this.hasCtf ? '/夺旗' : ''}${
                //           this.hasST ? '/渗透' : ''
                //       }`
                //     : matchMode == '2'
                //     ? `${this.hasCtf ? '夺旗' : ''}${this.hasST ? '/渗透' : ''}`
                //     : matchMode == '3' ?  '问答题' : '攻防plus';
            }
        },
        {
            title: '状态',
            key: 'statusCHName',
            minWidth: 90,
            render: (h, params) => {
                return h(
                    'Tooltip',
                    {
                        class: 'ivu-table-cell-tooltip',
                        props: {
                            disabled: params.row.status !== 'error',
                            content: params.row.note,
                            transfer: true
                        },
                        style: {
                            color: this.setColor(params.row)
                        }
                    },
                    [
                        h(
                            'span',
                            { class: 'ivu-table-cell-tooltip-content' },
                            params.row.statusCHName
                        )
                    ]
                );
            }
        },
        {
            title: '验证状态',
            key: 'statusName',
            minWidth: 90,
            show:false,
            render: (h, params) => {
                return h(
                    'Tooltip',
                    {
                        class: 'ivu-table-cell-tooltip',
                        props: {
                            disabled: params.row.verify !== 'error',
                            content: params.row.msg,
                            transfer: true
                        },
                        style: {
                            color: this.setScriptColor(params.row)
                        },
                        on: {
                            'on-popper-show': () => {
                                this.getErrorMessage(params.row);
                            }
                        }
                    },
                    [
                        h(
                            'span',
                            { class: 'ivu-table-cell-tooltip-content' },
                            params.row.statusName
                        )
                    ]
                );
            }
        },
        {
          title:'上报状态',
          key:'reportedStatus',
          show:() => {
            return this.distributed
          },
          filter:(reportedStatus) => {
            return ['0', '1'].includes(reportedStatus)
              ? '上报失败'
              : reportedStatus === '2'
              ? '上报成功'
              : '未上报'
          },
          setColor:(reportedStatus) => {
            return ['0', '1'].includes(reportedStatus)
              ? 'var(--status-no)'
              : reportedStatus === '2'
              ? 'var(--status-yes)'
              : 'var(--status-pre)'
          },
          disabled:(data) => {
            return !['0', '1'].includes(data.reportedStatus)
          },
          tooltip:true,
          tooltipKey:'reportedMsg'
        },
        {
          title:'检测脚本',
          key:"scriptName",
          minWidth:50,
          tooltip:true
        },
        {
            title: '验证类型',
            key: 'flagType',
            minWidth: 60,
            tooltip: true,
            filter: (flagType) => {
                return this.typeFilter(flagType);
            }
        },
        {
            type: 'Tag',
            title: '需要环境',
            minWidth: 80,
            key: 'imageId',
            filter: (imageId) => {
                return imageId ? '是' : '否';
            },
            setColor: (imageId) => {
                return imageId ? 'var(--status-yes)' : 'var(--status-no)'
            }
        },
        {
            type: 'link',
            title: '解题思路',
            key: 'writeUpName',
            minWidth: 100,
            tooltip: true,
            setPath: (data) => {
                return '/api/minio/download?path=' + data.writeUpPath;
            }
        },
        // {
        //     type: 'Tag',
        //     title: '有解题思路文档',
        //     key: 'writeUpPath',
        //     value: 'YorN',
        //     filter: (writeUpPath) => {
        //         return writeUpPath ? '是' : '否';
        //     },
        //     setColor: (writeUpPath) => {
        //         return writeUpPath ? '#307CED' : 'rgba(255,255,255,0.4000)';
        //     }
        // },
        // {
        //     type: 'Tag',
        //     value: 'YorN',
        //     title: '有附件',
        //     key: 'attachmentPath',
        //     filter: (attachmentPath) => {
        //         return attachmentPath ? '是' : '否';
        //     },
        //     setColor: (attachmentPath) => {
        //         return attachmentPath ? '#307CED' : 'rgba(255,255,255,0.4000)';
        //     }
        // },
        {
            type: 'link',
            title: '附件',
            minWidth: 50,
            tooltip: true,
            key: 'attachmentName',
            setPath: (data) => {
                return '/api/minio/download?path=' + data.attachmentPath;
            }
        },

        // {
        //     title: '设计者',
        //     key: 'creatorName',
        //     minWidth: 50,
        //     tooltip: true
        // },
        {
          title: '题目用途',
          key: 'application',
          minWidth: 60,
          tooltip: true,
          filter: (val) => {
            return this.applist[val];
          }
        },
        {
            title: '可见范围',
            key: 'visibility',
            minWidth: 60,
            tooltip: true,
            filter: (visible) => {
                return this.setVisibility(visible).text;
            },
            setColor: (visible) => {
                return this.setVisibility(visible).color;
            }
        },
        {
            title: '描述',
            key: 'description',
            minWidth: 50,
            tooltip: true
        },
        {
            title: '操作',
            width: 150,
            slot: 'action',
            opList: [
                {
                    txt: '脚本',
                    setColor: (data) => {
                        return data.verifyScriptId ? '#3f69b3' : '#e38100';
                    },
                    on:{
                      click:(data,e) => {
                        this.openCheck(data);
                      }
                    }
                },
                {
                    txt: '修改',
                    disabled: (data) => {
                        return this.setIsClick(data) ? true : false;
                    },
                    on:{
                      click:(data,e) => {
                        this.getCtfInfo(data);
                      }
                    }
                },
                {
                    txt: '删除',
                    type: 'delete',
                    tooltip: true,
                    title: '你确定要删除吗?',
                    disabled: (data) => {
                        return this.setIsClick(data) ? true : false;
                    },
                    on:{
                      click:(data,e) => {
                        this.delCtf(data.id);
                      }
                    }
                }
            ]
        }
    ],
      totalCount: 0,
      flavorList: [],
      ctfModal: {
        show: false,
        loading: true,
        type: 1,
        title: '创建主观题'
      },
      tagModal: {
        show: false,
        title: '标签'
      },
      urlModal: {
        show: false,
        title: 'url'
      },
      answerModal: {
        show: false,
        title: '答案'
      },
      fileModal: {
        show: false,
        title: '文件'
      },
      applist: {
        0: '考试和竞赛',
        1: '练习',
        2: '通用',
      },
      dictEntryList:[
        {key:2,value:'通用'},
        {key:0,value:'考试和竞赛'},
        {key:1,value:'练习'}
      ],
      
    
      formValidate: {
        answers: [
          {
            flag: '',
            flagMatchType: '0',
            score: 0
          }
        ],
        virtualization: 'kvm',
        defensivePort: '',
        attackScript: '',
        defenseScript: '',
        name: '',
        category: '',
        score: 1,
        // hidden: '0',
        description: '',
        // needEnv: '1',
        imageId: '',
        imageName: '',
        flavorRef: '',
        flavorName: '',
        application:'0',
        visibility: 'share',
        flagType: '1',
        submitFlag: '1',
        matchMode: '2',
        rangeId: '',
        port: '80',
        flagTxt: '',
        flagMatchType: '0',
        flagPath: '',
        writeUpName: '',
        // writeUpFileRecordId: "",
        writeUpPath: '',
        dockerContent: { tempId: '', dockerName: '', dockerPath: '', flagPath: '', cmd: '' }
      },
      FormValidate: {
        //新接口创建主观题不需要needEnv字段,并且传入会出问题,此数据仅仅为了保留原有的页面判断逻辑
        needEnv: '1',
        ImageSource: '1'
      },
      ruleValidate: {
        name: [
          { required: true, max: 128, message: '题目名称长度为1-128个字符', trigger: 'change,change' },
          {
            validator: validateName,trigger: 'change'
          }
        ],
        application: [
          {
            required: true,
            message: '题目用途不能为空',
            trigger: 'change'
          }
        ],
        category: [
          {
            required: true,
            message: '类型不能为空',
            trigger: 'change'
          }
        ],
        virtualization: [
          {
            required: true,
            message: '虚拟化类型不能为空',
            trigger: 'change'
          }
        ],
        defensivePort: [
          {
            required: true,
            message: '防守端口不能为空',
            trigger: 'change'
          }
        ],
        attackScript: [
          {
            required: true,
            message: '重置攻击机脚本不能为空',
            trigger: 'change'
          }
        ],
        defenseScript: [
          {
            required: true,
            message: '重置防守机脚本不能为空',
            trigger: 'change'
          }
        ],
        score: [
          {
            required: true,
            type: 'number',
            message: '分值不能为空',
            trigger: 'change'
          },
          {
            validator: validateScore,
            trigger: 'change'
          }
        ],
        // hidden: [{
        // 	required: true,
        // 	message: '不能为空',
        // 	trigger: 'change'
        // }],
        flagPath: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        needEnv: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        ImageSource: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        imageId: [
          {
            required: true,
            message: '请选择镜像',
            trigger: 'change'
          }
        ],
        flavorRef: [
          {
            required: true,
            message: '请选择配额',
            trigger: 'change'
          }
        ],
        visibility: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        flagType: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        submitFlag: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        matchMode: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        port: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          },
          {
            validator: validatePort,
            trigger: 'change'
          }
        ],
        flagTxt: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        flag: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        flagMatchType: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.tempId': [
          {
            required: true,
            message: '运行环境不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.dockerName': [
          {
            required: true,
            message: 'docker文件不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.flagPath': [
          {
            required: true,
            message: 'flag路径不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.cmd': [
          {
            required: true,
            message: 'docker运行命令及参数不能为空',
            trigger: 'change'
          }
        ]
      },
      imageList: [],
      uploadAction: '/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs',
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      uploadList: [],
      uploaderror: false,
      filename: '',
      showTip: false,
      speed: 0,
      // 显示
      showDataList: false,
      showDefImg: false,
      // 详情
      detailModal: false,
      curQues: {},
      //附件
      attachmentFile: '',
      curSaveFile: '',
      dockerList: [], //docker模板
      uploadDockerUrl: '/api/minio/upload?bucket=docker-image-file',
      uploadDockerList: [],
      dockerFilename: '', // docker文件名
      proSetInterval: '',
      saveTargetStatusArr: [], //储存中间状态数据
      data1: [
        {
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        },
        {
          name: 'Joe Black',
          age: 30,
          address: 'Sydney No. 1 Lake Park',
          date: '2016-10-02'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        }
      ],
      columns1: [
        {
          title: 'Name',
          key: 'name'
        },
        {
          title: 'Age',
          key: 'age'
        },
        {
          title: 'Address',
          key: 'address'
        }
      ],
      imageList1: [], // kvm
      imageList2: [], // docker
    };
  },
  computed: {
    isOwn: function() {
      return this.USER_ID == this.formValidate.creator || !this.formValidate.creator;
    },
    distributedRange() {
      return this.$store.state.user.distributedRange;
    },
    ...mapGetters(['hasAWD', 'hasST', 'hasCtf','hasAWDPlus']),
    stDrill () { // 渗透
      return this.$store.getters.getMenuName('stDrill');
    },
    awdContest () { // 攻防
      return this.$store.getters.getMenuName('awdContest');
    },
    awdPlusContest () { // 攻防Plus
      return this.$store.getters.getMenuName('awdPlusContest');
    },
    ctfContest () { // 夺旗
      return this.$store.getters.getMenuName('ctfContest');
    },
    matchModeList(){
      return [
        {
          label:[this.awdContest,this.ctfContest,this.stDrill].filter(name => name).join('/'),
          value:"1"
        },
        {
          label:'CTF题',//[this.ctfContest,this.stDrill].filter(name => name).join('/'),
          value:"2"
        },
        {
          label:'问答题',
          value:"3"
        },
        {
          label:this.awdPlusContest,
          value:"4"
        }
      ].filter(item => item.label)
    },
  },
  filters: {},
  methods: {
    getApplications(){

      experType('purpose_question').then((res) => {
        if (res.code === 1) {
         
          let attribute = res.attribute.attribute
          if(attribute && attribute.length>0){
            let dictEntryList = attribute[0].dictEntryList||[]
            if(dictEntryList && dictEntryList.length>0) {
              this.applist = {}
              this.dictEntryList = []
            }
         
            dictEntryList.forEach((item)=>{
              let key = Number(item.dictid)
              if(key!=3){
                this.applist[key] = item.dictname
                this.dictEntryList.push({key:key+"",value:item.dictname})
              }
       
            })
          }
        }
      })
    },
    getMatchMode(matchMode){
      let data = this.matchModeList.find(item => item.value === matchMode);
      return data ? data.label : '-'
    },
    // 获取配置的checkerList
    getCheckerList() {
      return new Promise((resolve) => {
        loadConfiguration({
          pageSize: 2147483646,
          type: 'vulnerability'
        })
          .then(({ code, data, message }) => {
            if (code === 1) {
              this.checkerList = data.items;
            } else {
              if (message) {
                this.$Message.warning(message);
              }
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    jinru() {
      this.hoverCdraBol = true;
    },
    yichu() {
      this.hoverCdraBol = false;
      this.configurationInformation = false;
      this.cardPanelLeft = '0';
      this.cardPanelTop = '0';
    },
    mouseLeaveConfiger(ev, value) {
      clearTimeout(this.optionOutEvent);
      this.optionOutEvent = setTimeout(() => {
        if (!this.hoverCdraBol) {
          this.configurationInformation = false;
          this.cardPanelLeft = '0';
          this.cardPanelTop = '0';
        }
      }, 300);
    },
    mouseOverConfiger(e, value) {
      clearTimeout(this.optionHoverEvent);
      this.optionHoverEvent = setTimeout(() => {
        if (this.hoverCdraBol) {
          return;
        }
        this.configurationInformation = true;
        this.cardPanelLeft = e.layerX + 30 + 'px';
        this.cardPanelTop = e.layerY + 35 + 'px';
        //查询配置详细信息
        let template = this.checkerList.find((item) => {
          return item.id === value;
        });
        if (template) {
          this.configPanel.configName = template.name;
          this.configPanel.configPath = template.path;
          this.configPanel.configSystype = template.sysType;
          this.configPanel.configArg = template.argArr;
          this.configPanel.configCmd = template.cmd;
          this.configPanel.protocol = template.protocol;
          this.configPanel.serverPort = template.serverPort;
          this.configPanel.language = template.language;
          this.configPanel.configDescription = template.description;
          this.configPanel.configCreateTime = template.createTime;
          this.configPanel.configCreatorName = template.creatorName;
        }
      }, 300);
    },
    // 删除delflag
    delflag(index) {
      this.flagNumber--;
      if (this.formValidate.answers.length === 1) {
        this.$Message.warning('至少需要一个flag');
        return;
      }
      this.formValidate.answers.splice(index, 1);
    },
    //增加flag
    addFlag() {
      this.flagNumber++;
      this.formValidate.answers.push({
        flag: '',
        flagMatchType: '0',
        score: 0,
        no: this.flagNumber || 1
      });
    },
    // 上报主观题
    reportedQuestions() {
      if (this.selectQuestions.length == 0) {
        this.$Message.warning('请选择主观题');
        return;
      }
      let questionIds = [],
        imageIds = [],
        flavorIds = [];
      this.selectQuestions.forEach((question) => {
        questionIds.push(question.id);
        if (question.flavorRef) {
          flavorIds.push(question.flavorRef);
        }
        if (question.imageId) {
          imageIds.push(question.imageId);
        }
      });
      reportedQuestions({
        images: imageIds,
        flavors: flavorIds,
        subjects: questionIds
      })
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.$Message.info('上报主观题成功');
          this.queryCtfList();
          this.selectQuestions = [];
          this.selectAllQuestion = false;
          this.ctfList.forEach((item) => this.$set(item, '_checked', false));
        })
        .catch(() => {
          this.$Message.error('上报主观题异常');
        });
    },
    //选择导出用户
    handleCheckAllQuestion(e) {
      this.selectAllQuestion = e;
      this.ctfList.forEach((question) => {
        this.checkSingleQuestion(e, question);
      });
    },
    checkSingleQuestion(e, question) {
      if (e && !this.selectQuestions.map((question) => question.id).includes(question.id)) {
        this.selectQuestions.push(question);
      } else if (!e && this.selectQuestions.map((question) => question.id).includes(question.id)) {
        let index = this.selectQuestions.findIndex((item) => question.id == item.id);
        this.selectQuestions.splice(index, 1);
      }
      let checkudQuestion = this.ctfList.find((item) => item.id == question.id);
      if (checkudQuestion) {
        this.$set(checkudQuestion, '_checked', e);
      }
      if (this.ctfList.length > 0 && this.ctfList.every((question) => question._checked === true)) {
        this.selectAllQuestion = true;
      } else {
        this.selectAllQuestion = false;
      }
    },

    // 获取题目类型
    getQuestionType() {
      experType('questionType')
        .then(({ code, message, attribute = [] }) => {
          if (code !== 1) {
            this.$Message.warning(message);
          } else {
            this.questionTypeList = ((attribute.attribute[0] || {}).dictEntryList || []).map(
              (item) => {
                return {
                  dictname: unescape(item.dictname)
                };
              }
            );
          }
        })
        .catch(() => {
          this.$Message.error('获取题目类型异常');
        });
    },
    // 设置样式
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      let num = this.fullHeight - 200;
      this.setHei = this.fullHeight - 60 - 75 + 'px';
      this.query.pageSize = Math.floor(num / 96);
    },
    searchCreatedByMe(val) {
      this.query.pageIndex = 1;
      if (this.creatByMeModal) {
        this.queryCtfInfo.creator = this.USER_ID;
        this.queryCtfInfo.self = 1;
      } else {
        this.queryCtfInfo.creator = '';
        this.queryCtfInfo.self = 0;
      }
      // this.iconModelInput = ''
      this.queryCtfList();
    },
    refreshCtfQuesList() {
      this.query = {
        pageIndex: 1,
        pageSize: this.query.pageSize
      };
      (this.queryCtfInfo = {
        rangeId: '',
        matchMode: '',
        needEnv: '',
        // isExistTips: '',
        visibility: '',
        name: '',
        imageName: '',
        flagType: ''
      }),
        (this.creatByMeModal = false);
      this.queryCtfList();
    },
    queryCtfList(isRefresh) {
      if (!isRefresh) {
        this.tableLoading = true;
        // 非刷新操作才需要展示等待中的画面
        this.showDataList = false;
        this.showDefImg = true;
      }
      clearInterval(this.proSetInterval);
      this.saveTargetStatusArr = [];
      this.ctfList = [];
      let schparam = JSON.parse(JSON.stringify(this.queryCtfInfo))
      if(this.queryCtfInfo.applicationList && this.queryCtfInfo.applicationList.length>0){
        schparam.applicationList = this.queryCtfInfo.applicationList.map(item=>{
          return Number(item)
        })
      }
      
      queryCtfList(schparam, this.query).then(async (data) => {
        if (data.code == 1) {
          this.totalCount = +data.data.total;
          let items = [];
          if (data.data.items) {
            items = data.data.items;
            let questionIds = this.selectQuestions.map((question) => question.id);
            let checkedNum = 0;
            items.forEach((question) => {
              if (questionIds.includes(question.id)) {
                this.$set(question, '_checked', true);
                checkedNum++;
              } else {
                this.$set(question, '_checked', false);
              }
            });
            if (checkedNum && items.length === checkedNum) {
              this.selectAllQuestion = true;
            } else {
              this.selectAllQuestion = false;
            }
          }
          await this.getReportedStatus_mixins(items).then();
          items.forEach(async (item) => {
            await this.getScriptResource(item).then();
            item.status == 'saving'
              ? this.$set(item, 'statusCHName', '创建中')
              : item.status == 'create_ing'
              ? this.$set(item, 'statusCHName', '镜像生成中')
              : item.status == 'error'
              ? this.$set(item, 'statusCHName', '创建失败')
              : this.$set(item, 'statusCHName', '创建成功');
            item.verify == 'error'
              ? this.$set(item, 'statusName', '验证失败')
              : item.verify == 'active'
              ? this.$set(item, 'statusName', '验证成功')
              : item.verify == 'verify_ing'
              ? this.$set(item, 'statusName', '验证中')
              : this.$set(item, 'statusName', '未验证');
            if (
              item.status == 'saving' ||
              item.status == 'create_ing' ||
              item.verify == 'verify_ing'
            ) {
              this.saveTargetStatusArr.push(item);
            }
          });
          if (this.saveTargetStatusArr.length > 0) {
            this.proSetInterval = setInterval(() => {
              this.queryCtfList(true);
            }, 3000);
          } else {
            clearInterval(this.proSetInterval);
          }
          this.ctfList = items;
          if (items.length > 0) {
            this.showDataList = true;
            this.showDefImg = false;
          } else {
            this.showDataList = false;
            this.showDefImg = true;
          }
          this.setMainOrBranch();
        } else {
          this.$Message.warning(data.message);
          this.showDataList = false;
          this.showDefImg = true;
        }
        this.tableLoading = false;
      }).catch(error => {
        this.tableLoading = false;
      });
    },
    addQuestionTip() {
      //点击创建主观题的回调
      this.ctfModal.show = true;
      this.ctfModal.type = 1;
      this.ctfModal.title = '创建主观题';
      this.filename = '';
      this.showTip = false;
      this.uploaderror = false;
      this.attachmentFile = '';
      this.curSaveFile = '';
      this.initForms();
    },
    delCtf(id) {
      delCtf(id).then((data) => {
        if (data.code == 1) {
          this.$Message.info({
            content: '删除主观题完成',
            duration: 3
          });
          this.query.pageIndex =
            this.ctfList.length == 1 && this.query.pageIndex > 1
              ? this.query.pageIndex - 1
              : this.query.pageIndex;
          this.queryCtfList();
          this.distributed && this.$refs.searchTable.delSelectItem(id)
        } else {
          this.$Message.warning(data.message);
        }
      });
    },
    //获取上传附件信息
    getAttachmentFile(file) {
      if (file) {
        this.formValidate.attachmentName = file.info.originalName;
        this.formValidate.attachmentPath = file.data;
      } else {
        this.attachmentFile = '';
      }
    },

    modifyCtf() {
      const newObj = JSON.parse(JSON.stringify(this.formValidate));
      if (this.formValidate.dockerContent != '') {
        newObj.dockerContent = JSON.stringify(this.formValidate.dockerContent);
      }
      modifyCtf(newObj, this.formValidate.id)
        .then((data) => {
          if (data.code === 1) {
            this.$Message.info({
              content: '修改主观题成功',
              duration: 3
            });
            if (this.FormValidate.needEnv === '1') {
              // 需要环境
              if (this.formValidate.scriptId) {
                // 存在脚本，需要绑定题目与脚本的关系
                this.setQuestionScript(true, this.formValidate.id, this.formValidate.scriptId);
              } else {
                // 不存在脚本，清空题目与脚本的关系
                this.setQuestionScript(false, this.formValidate.id, this.formValidate.scriptId);
              }
            }
            this.cancelLoading('ctfModal');
            this.ctfModal.show = false;
            this.queryCtfList();
            this.initForms();
          } else {
            this.$Message.error(data.message);
            this.cancelLoading('ctfModal');
          }
        })
        .catch((error) => {
          this.$Message.error('修改失败，请检查网络设置');
        });
    },
    setQuestionScript(isBind, questionId, scriptId) {
      if (isBind) {
        // 绑定题目与脚本关系
        bindScriptResource({
          idList: scriptId,
          objectId: questionId,
          type: 'sub'
        })
          .then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message);
            }
          })
          .catch(() => {
            this.$Message.error('绑定主观题与检测脚本异常');
          });
      } else {
        // 解绑题目关联的所有脚本
        deleteScriptResource({
          objectId: questionId,
          type: 'sub'
        })
          .then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message);
            }
          })
          .catch(() => {
            this.$Message.error('解绑主观题与检测脚本关系异常');
          });
      }
    },
    getScriptResource(question) {
      return new Promise((resolve) => {
        getScriptResource({
          type: 'sub',
          id: question.id
        })
          .then(({ code, data = [] }) => {
            if (code === 1 && data.length) {
              let scriptId = data[0].scriptId;
              let template = this.checkerList.find((item) => item.id === scriptId);
              let scriptName = template ? template.name : '';
              this.$set(question, 'scriptId', scriptId);
              this.$set(question, 'scriptName', scriptName);
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    createCtf() {
      const newObj = JSON.parse(JSON.stringify(this.formValidate));
      if (this.formValidate.dockerContent != '') {
        newObj.dockerContent = JSON.stringify(this.formValidate.dockerContent);
      }
      createCtf(newObj)
        .then((data) => {
          this.cancelLoading('ctfModal');
          if (data.code == 1) {
            this.$Message.info({
              content: '创建主观题完成!',
              duration: 3
            });
            if (this.FormValidate.needEnv === '1' && this.formValidate.scriptId) {
              // 需要环境，存在脚本，需要绑定题目与脚本的关系
              this.setQuestionScript(true, data.data && data.data.id, this.formValidate.scriptId);
            }
            this.ctfModal.show = false;
            this.refreshCtfQuesList();
            this.initForms();
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error('添加失败，请检查网络设置');
        });
    },
    saveCtf() {
      //点击创建修改面板确定的回调
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          delete this.formValidate.needEnv; //创建和修改主观题时,删除不需要的参数,
          delete this.formValidate.ImageSource;
          if (this.formValidate.category === '安全运维') {
            this.formValidate.flagType = '2';
            this.formValidate.flagTxt = '';
            this.formValidate.flagPath = '';
            this.formValidate.submitFlag = 0;
          }
          if (this.FormValidate.needEnv === '0') {
            this.formValidate.imageId = '';
            this.formValidate.flavorRef = '';
            this.formValidate.imageName = '';
            this.formValidate.flavorName = '';
            this.formValidate.port = '';
          }
          if (this.formValidate.submitFlag === '0'&&this.formValidate.matchMode!='3') {
            this.formValidate.flagType = '3';
            this.formValidate.flagTxt = '';
          }
          if (this.formValidate.flagType === '0') {
            this.formValidate.flagPath = '';
          }
          // 只有攻防赛plus类型的docker需要添加防守机脚本
          if (this.formValidate.virtualization === 'docker') {
            if (this.formValidate.matchMode === '4') {
              this.formValidate.shell = JSON.stringify({
                attack: this.formValidate.attackScript,
                defense: this.formValidate.defenseScript
              });
            } else {
              this.formValidate.shell = JSON.stringify({ attack: this.formValidate.attackScript });
            }
          }
          //选择已有镜像和docker上传选其一
          if (this.FormValidate.ImageSource == '1') {
            this.formValidate.dockerContent = '';
          } else if (this.FormValidate.ImageSource == '0') {
            this.formValidate.imageId = '';
            this.formValidate.imageName = '';
          }
          if (this.formValidate.answers && this.formValidate.flagType == '0') {
            //固定flag
            let score = 0;
            this.formValidate.answers.forEach((item) => {
              if (item.score && typeof item.score === 'number') {
                score += item.score;
              }
            });
            if (score) {
              this.formValidate.score = score;
            }
          } else {
            // 不是固定flag不传 answers
            // 传[]后台并没有清掉,先前端传一个默认的，要不然修改验证类型时清不掉
            this.formValidate.answers = [
              {
                flag: '',
                flagMatchType: '0',
                id: '',
                no: 1,
                questionId: this.formValidate.id,
                score: 0
              }
            ];
          }
          let itemScriptId = this.checkerList.find(item => item.id == this.formValidate.scriptId)
            this.formValidate.scriptName = itemScriptId ? itemScriptId.name : '';
          if (!this.formValidate.chaId) {
            this.createCtf();
          } else {
            delete this.formValidate.chaId;
            this.modifyCtf();
          }
        } else {
          this.cancelLoading('ctfModal');
        }
      });
      this.flagNumber = 1;
    },
    getCtfInfo(data) {
      //点击修改按钮的回调
      // console.log(data);
      this.ctfModal.show = true;
      this.ctfModal.title = '修改主观题';
      this.ctfModal.type = 2;
      this.filename = '';
      this.showTip = false;
      this.uploaderror = false;
      this.formValidate = JSON.parse(JSON.stringify(data));
      // 攻防赛都需要提交flag
      this.$set(this.formValidate, 'submitFlag', String(data.matchMode === '4' ? 1 : data.submitFlag));
      this.$set(this.formValidate, 'flagType', String(data.flagType));
      this.$set(this.formValidate, 'application', String(data.application));

      this.flagNumber = this.formValidate.answers.length;
      if (this.formValidate.shell) {
        try {
          let shell = JSON.parse(this.formValidate.shell);
          this.$set(this.formValidate, 'attackScript', shell.attack || '');
          this.$set(this.formValidate, 'defenseScript', shell.defense || '');
        } catch (e) {
          // 不做处理
        }
      }
      if (
        this.formValidate.flagTxt &&
        this.formValidate.answers.length == 1 &&
        this.formValidate.answers[0].score == 0
      ) {
        //有些多个flag旧数据误传第一个flag为空 兼容旧数据
        this.formValidate.answers.splice(0, 1);
      }
      if (
        this.formValidate.flagTxt != null &&
        this.formValidate.flagTxt != '' &&
        !(this.formValidate.answers && this.formValidate.answers.length)
      ) {
        var _that = this;
        let answers = {
          flag: _that.formValidate.flagTxt,
          flagMatchType: _that.formValidate.flagMatchType,
          score: _that.formValidate.score
        };

        this.formValidate.answers.push(answers);
        // this.formValidate.answers.flag=this.formValidate.flagTxt
        // this.formValidate.answers.flag=this.formValidate.flagTxt
      }
      if (data.dockerContent) {
        this.formValidate.dockerContent = JSON.parse(data.dockerContent);
        this.FormValidate.ImageSource = '0';
      } else this.FormValidate.ImageSource = '1';
      this.dockerFilename = this.formValidate.dockerContent.dockerName;
      this.formValidate.imageId || data.dockerContent
        ? (this.FormValidate.needEnv = '1')
        : (this.FormValidate.needEnv = '0');
      this.formValidate.submitFlag == 0
        ? (this.formValidate.submitFlag = '0')
        : (this.formValidate.submitFlag = '1');
      this.formValidate.chaId = true; //之前接口回来的有此字段,新接口无,添加此字段作为点击确定按钮走更新还是添加的回调
      this.formValidate.needEnv = '1'; // 通过修改时候的表单验证
      this.formValidate.ImageSource = '1'; //通过修改时候的表单验证
      this.filename = this.formValidate.writeUpName;
      if (data.attachmentPath) {
        //当前绑定的文件
        this.curSaveFile = {
          info: {
            originalName: this.formValidate.attachmentName
          },
          data: this.formValidate.attachmentPath
        };
      } else {
        this.attachmentFile = '';
        this.curSaveFile = '';
      }
    },
    initForms() {
      this.flagNumber = 1;
      this.formValidate = {
        answers: [
          {
            flag: '',
            flagMatchType: '0',
            score: 0
          }
        ],
        virtualization: 'kvm',
        defensivePort: '',
        attackScript: '',
        defenseScript: '',
        name: '',
        category: '',
        score: 0,
        // hidden: '0',
        description: '',
        needEnv: '1', //通过表单验证
        ImageSource: '1', //通过表单验证
        imageId: '',
        imageName: '',
        flavorRef: '',
        flavorName: '',
        application:'0',
        visibility: 'share',
        flagType: '0',
        submitFlag: '1',
        matchMode: '2',
        port: '80',
        flagTxt: '',
        flagMatchType: '0',
        flagPath: '',
        writeUpName: '',
        // writeUpFileRecordId: "",
        writeUpPath: '',
        dockerContent: { tempId: '', dockerName: '', dockerPath: '', flagPath: '', cmd: '' }
      };
      this.FormValidate = {
        needEnv: '1',
        ImageSource: '1'
      };
      this.dockerFilename = '';
      //		        this.$refs['formValidate'].resetFields();
      //当表单中使用了v-if隐藏某个输入框，表单的重置方法会报indexOf的错误
      this.$refs['formValidate'].fields.forEach(function(e) {
        if (e.fieldValue != undefined) {
          e.resetField();
        }
      });
    },
    changePage(page) {
      this.query.pageIndex = page;
      this.queryCtfList();
    },
    cancelLoading(name) {
      this[name].loading = false;
      setTimeout(() => {
        this[name].loading = true;
      });
    },
    cancel(name) {
      this.$refs[name].resetFields();
    },
    getAllImage1() {
      let obj = {
        virtualization: 'kvm'
      };
      let search = {
        pageIndex:1,
        pageSize:9999,
      }
      getallImage(obj,search).then(data => {
        if(data.code === 1) {
          this.imageList1 = data.data.items;
        }
      })
    },
    getAllImage2() {
      let obj = {
        virtualization: 'docker'
      };
      let search = {
        pageIndex:1,
        pageSize:9999,
      }
      getallImage(obj,search).then(data => {
        if(data.code === 1) {
          this.imageList2 = data.data.items;
        }
      })
    },
    getImageInfo(val) {
      if (!val) {
        return;
      }
      this.formValidate.imageId = val.value;
      this.formValidate.imageName = val.label;
      this.formValidate.flavorRef = '';
      let imageList = []
      if(this.formValidate.virtualization == 'kvm') {
        imageList = this.imageList1
      }else {
        imageList = this.imageList2
      }
      let curImages = imageList.filter((item) => item.id === val.value)[0];
      // console.log(curImages,'curImagescurImages');
      // console.log(this.flavorListCopy,'flavorListCopyflavorListCopy');
      this.flavorList = this.flavorListCopy.filter(
        (item) => item.ram >= Number(curImages.minRam) && item.disk >= Number(curImages.minDisk)
      );
      // console.log(this.flavorList,'this.flavorListthis.flavorList');
    },
    screenSelector(val) {
      if (!val) {
        return;
      }
      this.formValidate.imageId = val.value;
      this.formValidate.imageName = val.label;
      this.formValidate.flavorRef = '';
      let obj = {
        virtualization: this.formValidate.virtualization
      };
      let search = {
        pageIndex: 1,
        pageSize: 9999
      };
      getallImage(obj, search).then((data) => {
        if (data.code === 1) {
          let imageList = []
          if(this.formValidate.virtualization == 'kvm') {
            this.imageList1 = data.data.items
            imageList = this.imageList1
          }else {
            this.imageList2 = data.data.items
            imageList = this.imageList2
          }
          let curImages = imageList.filter((item) => item.id === val.value)[0];
          this.flavorList = this.flavorListCopy.filter(
            (item) => item.ram >= Number(curImages.minRam) && item.disk >= Number(curImages.minDisk)
          );
        }
      });
    },
    getAllFlavor() {
      const search = {
        pageIndex: 1,
        pageSize: 9999
      };
      getallFlavor(search).then((data) => {
        if (data.code === 1) {
          this.flavorList = data.data.items;
          this.flavorListCopy = data.data.items;
        }
      });
    },
    getFlavorInfo(val) {
      if (val) {
        this.formValidate.flavorRef = val.value;
        this.formValidate.flavorName = val.label;
      }
    },
    changeCategory(val) {
      if (val === '安全运维') {
        this.$set(this.formValidate, 'submitFlag', '0');
        this.$set(this.FormValidate, 'needEnv', '1');
      }
    },
    //改变题型
    setFormInfo(val) {
      if (val == '1') {
        this.FormValidate.needEnv = '1';
        this.formValidate.submitFlag = '1';
        this.formValidate.flagType = '1';
        this.formValidate.virtualization = 'kvm';
      } else if (val == '2') {
        this.FormValidate.needEnv = '1';
        this.formValidate.submitFlag = '1';
        this.formValidate.flagType = '0';
        this.formValidate.virtualization = 'kvm';
      } else if (val == '3') {
        this.FormValidate.needEnv = '0';
        this.formValidate.submitFlag = '0';
        this.formValidate.flagType = '3';
        this.formValidate.flagMatchType = '0';
        this.formValidate.virtualization = 'kvm';
      } else {
        this.FormValidate.needEnv = '1';
        this.formValidate.submitFlag = '1';
        this.formValidate.flagType = '0';
        this.formValidate.virtualization = 'kvm';
      }
    },
    //如果不需要部署环境，且需要提交Flag
    setFormInfo1(val) {
      if (val == '0') {
        this.formValidate.imageId = '';
        this.formValidate.flavorRef = '';
        this.formValidate.imageName = '';
        this.formValidate.flavorName = '';
        this.formValidate.port = '';
        this.formValidate.dockerContent = '';
        this.dockerFilename = '';
      } else {
        this.formValidate.port = '80';
      }
      if (val == '0' && (this.formValidate.submitFlag = '1')) {
        this.formValidate.flagType = '0';
      }
    },
    changeNeedSubmitFlag(val) {
      this.formValidate.flagTxt = '';
      this.formValidate.flagPath = '';
      if (val == '0') {
        //不需要提交flag时
        this.formValidate.flagType = '3';
      } else {
        if (this.formValidate.matchMode == '1') {
          this.formValidate.flagType = '1';
        } else {
          this.formValidate.flagType = '0';
        }
      }
    },
    handleFormatError() {
      this.showTip = true;
    },
    handleBeforeUpload() {
      this.uploadList = this.$refs.upload.fileList;
      this.showTip = false;
      return true;
    },
    getImageUrl(res) {
      if (res.code == 1) {
        let file = res;
        let src = file.data;
        this.uploaderror = false;
        this.filename = file.info.originalName;
        this.formValidate.writeUpPath = src;
        this.formValidate.writeUpName = file.info.originalName;
        // this.formValidate.writeUpFileRecordId = file.info.id;
      } else {
        this.$Message.warning(res.message);
      }
    },
    //清除解题思路
    clearDoc() {
      this.filename = '';
      this.formValidate.writeUpPath = '';
      this.formValidate.writeUpName = '';
      // this.formValidate.writeUpFileRecordId = '';
    },
    getProgress(progressEvent) {
      var aaspeed = Number(progressEvent.loaded - this.loaded) || 0;
      this.loaded = progressEvent.loaded;
      if (aaspeed > 1024 * 1024) {
        this.speed = (Math.round((aaspeed * 100) / (1024 * 1024)) / 100).toString() + 'MB/s';
      } else {
        this.speed = (Math.round((aaspeed * 100) / 1024) / 100).toString() + 'KB/s';
      }
    },
    getFileSize(size) {
      let fileSize;
      if (size > 1024 * 1024) {
        fileSize = (Math.round((size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
      } else {
        fileSize = (Math.round((size * 100) / 1024) / 100).toString() + 'KB';
      }
      return fileSize;
    },
    handleUploadSize() {
      this.showTip = true;
    },
    // 按钮点击状态
    setReBtnStatus(params) {
      let userid = params.creator;
      if (userid === this.USER_ID || this.isRootDesigner) {
        return false;
      } else {
        return true;
      }
    },
    // 计算index
    handleProIndex(key) {
      return (this.query.pageIndex - 1) * this.query.pageSize + key + 1;
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 'share') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 'private') {
        text = '个人';
        color = '#FFA500';
      } else if (val === 'public') {
        text = '系统';
        color = '#4169E1';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    // 设置下载icon
    handleDownIcon(val) {
      if (val) {
        return require('../../../../assets/project/download-h.png');
      } else {
        return require('../../../../assets/project/download-s.png');
      }
    },
    // 设置知否可点击
    setIsClick(item) {
      if (item.visibility === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return true //{'pointer-events': 'none'};
      }
    },
    setImgSrc(item) {
      if (item.visibility === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../../../assets/project/modifys.png');
      } else {
        return require('../../../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if (item.visibility === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../../../assets/project/delNote-d.png');
      } else {
        return require('../../../../assets/project/delNote-h.png');
      }
    },
    showDetail(item) {
      this.detailModal = true;
      this.curQues = JSON.parse(JSON.stringify(item));
      if (this.curQues.matchMode === '4') {
        try {
          let shell = JSON.parse(this.curQues.shell);
          this.curQues.attackScript = shell.attack;
          this.curQues.defenseScript = shell.defense;
        } catch (e) {
          // 不做处理
        }
      }
      if (this.curQues.dockerContent) {
        let result = JSON.parse(this.curQues.dockerContent);
        let findRes = this.dockerList.find((item) => {
          return item.id == result.tempId;
        });
        this.$set(this.curQues, 'dockerEnvName', findRes.name);
      }
    },
    changePublic(val) {
      //没用
      if (val == 1 && this.ctfModal.type == 1) {
        this.formValidate.imageId = '';
        this.formValidate.flavorRef = '';
        this.formValidate.imageName = '';
        this.formValidate.flavorName = '';
      }
    },
    typeFilter(val) {
      let str = '';
      switch (val) {
        case '0':
          str = '固定Flag';
          break;
        case '1':
          str = '非固定Flag';
          break;
        case '2':
          str = 'Checker';
          break;
        case '3':
          str = '提交报告';
          break;
        default:
          str = '未定义类型';
          break;
      }
      return str;
    },
    handleBeforeUploadDocker() {
      this.uploadDockerList = this.$refs.uploadDocker.fileList;
      this.speed = 0;
      return true;
    },
    getDockerUrl(res) {
      if (res.code === 1) {
        this.formValidate.dockerContent.dockerName = res.info.originalName;
        this.formValidate.dockerContent.dockerPath = res.data;
        this.dockerFilename = res.info.originalName;
      }

      this.uploadDockerList = [];
    },
    clearDocker() {
      this.dockerFilename = '';
      this.formValidate.dockerContent.dockerName = '';
      this.formValidate.dockerContent.dockerPath = '';
    },
    getAllDocker() {
      return
      let search = {
        pageIndex: 1,
        pageSize: 99999
      };
      getAllDocker(search).then((res) => {
        if (res.code === 1) {
          this.dockerList = res.data.items;
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    setImageSource() {
      if (this.formValidate.chaId) {
        this.formValidate.dockerContent = {
          tempId: '',
          dockerName: '',
          dockerPath: '',
          flagPath: '',
          cmd: ''
        };
        this.dockerFilename = '';
      }
    },
    addImage() {
      this.$refs.check.addImage();
    },
    setColor(item) {
      let color = 'var(--status-pre)';
      switch (item.status) {
        case 'error': // 创建失败
          color = 'var(--status-no)';
          return color;
          break;
        case 'create_ing': // 镜像生成中
          color = 'var(--status-ing)';
          return color;
          break;
        case 'saving': // 创建中
          color = 'var(--status-ing)';
          return color;
          break;
        case 'active': // 创建成功
          color = 'var(--status-yes)';
          return color;
          break;
        default:
          return color;
      }
    },
    setScriptColor(item) {
      let color = 'var(--status-pre)';
      switch (item.verify) {
        case 'none': // 未验证
          color = 'var(--status-pre)';
          return color;
          break;
        case 'verify_ing': // 验证中
          color = 'var(--status-ing)';
          return color;
          break;
        case 'active': // 验证成功
          color = 'var(--status-yes)';
          return color;
          break;
        case 'error': // 验证失败
          color = 'var(--status-no)';
          return color;
          break;
        default:
          return color;
      }
    },
    openCheck(item) {
      item.subFlag = true; //标志为主观题
      this.$refs.check.openCheck(item);
    },
    getErrorMessage(item) {
      if (item.verify == 'error' || item.verify == 'active') {
        let query = {
          type: 'verify_question'
        };
        getOperateInfo(item.id, query)
          .then((res) => {
            if (res.code == 1) {
              let msg = res.data.msg;
              this.$set(item, 'msg', msg);
            } else {
              this.$Message.error({ content: '获取原因失败', duration: 3 });
            }
          })
          .catch((err) => {
            this.$message.error({ content: err.message, duration: 3 });
          });
      }
    },
    //查询所有分靶场信息
    queryAllRange() {
      
      getRangeAll().then((res) => {
        if (res.code === 1) {
          let mainRange = res.data.items.find((item) => {
            return item.level== 'LOCAL';
          });
          this.mainRange = mainRange.name || '选择靶场';
          this.rangeAllList = res.data.items;
          // ('--------查询所有分靶场信息----------',this.rangeAllList,mainRange)
        }
      });
    },
    setMainOrBranch() {
      let res = this.rangeAllList.find((item) => {
        return item.id == this.queryCtfInfo.rangeId;
      });
      if (res && res.level != 'LOCAL') {
        this.mainRangeflag = false; // 分靶场
      } else {
        this.mainRangeflag = true; // 主靶场
      }
    },
    searchItem() {
      this.queryCtfList();
    }
  },
  async mounted() {
    await this.getApplications()// 获取字典中的题目用途
    await this.getCheckerList();
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    this.queryCtfList();
    this.getAllImage1();
    this.getAllImage2();
    this.getAllFlavor();
    this.getQuestionType();
    this.getAllDocker(); // 获取所有的docker运行环境
    this.queryAllRange();
    
  },
  watch: {
    show: function(val) {
      if (val) {
        this.queryCtfList();
      }
    }
  },
  created() {},
  beforeDestroy() {
    clearInterval(this.proSetInterval);
  }
};
</script>
<style scoped>
.ctfQuestion-warp {
  background-color: var(--card-body-bgcolor);
  border-radius: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.page-content {
  flex: auto;
  margin-top: 20px;
	/* overflow-x: hidden;
		overflow-y: auto; */
  /* max-height: calc(100vh - 220px); */
  width: 100%;
  font-size: 14px;
  overflow-x: hidden;
  overflow-y: auto;
  margin-top: 20px;
}
.content-wrap {
  font-size: 14px;
}

.project-item {
  width: 100%;
  border-radius: 4px;
  border: 2px solid rgb(231, 231, 241);
  padding: 10px 15px;
  margin-bottom: 15px;
}

.item-first-line {
  display: flex;
  justify-content: space-between;
}

.project-name-state {
  display: flex;
  justify-content: flex-start;
}

.project-name {
  font-size: 16px;
  font-weight: 600;
  width: 110px;
  white-space: nowrap;
  text-overflow: ellipsis;
  /* overflow: hidden; */
  word-break: break-all;
}

.project-status-text {
  font-weight: 600;
  font-size: 14px;
  margin-left: 25px;
  display: flex;
  justify-content: flex-start;
}

.btn-icon-wrap {
  display: flex;
  justify-content: flex-end;
}

.click-icon {
  cursor: pointer;
  height: 22px;
  margin-left: 12px;
}

.project-other-info {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  margin-top: 8px;
  color: rgba(51, 51, 51, 0.4);
  font-weight: bold;
}

.sendMsgContent {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  width: calc(100vh - 750px);
}

.floatWrap {
  width: calc(100% - 224px);
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: flex-end;
  /* margin-top: -32px; */
  /* padding-top: 20px; */
  margin-left: 224px;
  margin-top: 20px;
}
.floatWrap > div,
.floatWrap > button,
.floatWrap > label {
  margin-bottom: 10px;
}
#quesDetail {
  display: table;
  width: 100%;
  border: 1px solid var(--table-border);
  table-layout: fixed;
  word-break: break-all;
}

#quesDetail p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}

#quesDetail p span {
  display: table-cell;
  border-bottom: 1px solid var(--table-border);
}
.chose-wrap {
  display: flex;
  justify-content: space-between;
  padding: 3px 8px;
  background-color: var(--table-tr-hover-color);
  align-items: center;
  margin-top: 10px;
}

.chose-name {
  width: 300px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chose-s-icon {
  width: 15px;
  height: 17px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}

.chose-s2-icon {
  width: 13px;
  height: 15px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}
.AddImageBtn {
  position: absolute;
  right: 20px;
  top: 5px;
}
.SelForm {
  position: relative;
}

.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.ios-alert1 {
  position: absolute;
  top: 0px;
  right: -24px;
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.text-ellipsis-name {
  width: 100px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
}
</style>
<style>
/* #_tableId .ivu-table thead th {
		height: 30px !important;
		background: #ebeff6;
		color: #000;
		font-size: 16px;
		box-sizing: border-box;
	}
	#_tableId .ivu-table tr{
		height: 30px !important;
	}
	#_tableId .ivu-table-body{
		margin-top: -20px;
	}

	.forTooltip .ivu-tooltip-inner{
		max-height:300px!important;
		overflow-y:auto;
	} */
</style>
